//
//  PushGoodsVC.m
//  rrbi
//
//  Created by mac book on 2018/12/5.
//

#import "PushGoodsVC.h"

#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import "UpdatePhotoCollectionViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"

#define maxCount  1


#define FooterButton_Height    80/HEIGHT_6S_SCALE
#define HeaderView_Height    50/HEIGHT_6S_SCALE

#define Space_X    15/WIDTH_6S_SCALE
#define PhotoView_H    130/HEIGHT_6S_SCALE



@interface PushGoodsVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    
    CGFloat _itemWH;
    CGFloat _margin;
}
@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *platformArray;
@property(nonatomic,strong)NSMutableArray *storeArray;
@property (nonatomic, strong) NSDictionary *mainDict;

@property(nonatomic,strong)UIView *photoView;
@property(nonatomic,strong)UIButton *platformBtn;
@property(nonatomic,strong)UIButton *storeBtn;
@property(nonatomic,strong)UITextField *nameTF;//商品名称
@property(nonatomic,strong)UITextField *priceTF;//进价
@property(nonatomic,strong)UITextField *salesPriceTF;//售价
@property(nonatomic,strong)UITextField *membersPriceTF;//会员价
@property(nonatomic,strong)UITextField *packingPriceTF;//包装费
@property(nonatomic,strong)UITextField *countTF;//数量
@property(nonatomic,strong)UITextField *minBuyPriceTF;//最低购买数量
@property(nonatomic,strong)UITextField *kuCunRemindTF;//库存提醒
@property(nonatomic,strong)UITextField *goodsMiaoSuTF;//商品描述
@property(nonatomic,strong)UITextField *specialTF;//特色标签
@property(nonatomic,strong)UILabel *shangJiaLabel;//是否上架
@property(nonatomic,strong)UIButton *commitbtn;


@property (nonatomic, copy) NSString *typeId;
@property (nonatomic, copy) NSString *platformId;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (strong, nonatomic) CLLocation *location;

//@property (strong, nonatomic) NSMutableArray *photosArray;
//@property (strong, nonatomic) NSMutableArray *assetsArray;
@end

@implementation PushGoodsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.isFaBu) {
         self.title = @"发布商品";
    } else {
         self.title = @"编辑商品";
    }
   
    self.platformArray = [NSMutableArray array];
    self.storeArray = [NSMutableArray array];
    _selectedPhotos = [NSMutableArray array];
    
    [self querySelectData];
    
    
}
-(void)creatSubViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) ) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [self creatFooterView];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    [self initTalbeViewSubview];
}

-(void)querySelectData{
    
    [self showprogressHUD];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //    "ince":"getshopcat","sid":"101","parent_id":"0",
        NSDictionary* arg = @{@"ince":@"getshopcat",
                              @"sid":[UserModel sharedInstanced].ru_Id,
                              @"parent_id":@"0"
                              };
        [NetRepositories searchGoods:arg complete:^(EnumNetResponse react, NSArray *list, NSString *message, NSDictionary *mainDict) {
            
            self.storeArray = [NSMutableArray arrayWithArray:list];
            [self.tableView reloadData];
        }];
        dispatch_group_leave(group);
    });
    dispatch_group_enter(group);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //    "ince":"get_category","sid":"101","parent_id":"0",
        NSDictionary* arg = @{@"ince":@"get_category",
                              @"sid":[UserModel sharedInstanced].ru_Id,
                              };
        [NetRepositories searchPlatformGoods:arg complete:^(EnumNetResponse react, NSArray *list, NSString *message, NSDictionary *mainDict) {
            
            self.platformArray = [NSMutableArray arrayWithArray:list];
            [self.tableView reloadData];
        }];
        dispatch_group_leave(group);
    });
    
    
    if (!self.isFaBu) {

        dispatch_group_enter(group);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //    "ince":"get_category","sid":"101","parent_id":"0",
        NSDictionary* arg = @{@"ince":@"get_edit_goods",
                              @"goods_id":self.goodsId,
                              };
        [NetRepositories searchPlatformGoods:arg complete:^(EnumNetResponse react, NSArray *list, NSString *message, NSDictionary *mainDict) {
            self.mainDict = [mainDict objectForKey:@"info"];
            [self editorVCAssignmentWithDict:self.mainDict];
        }];
        dispatch_group_leave(group);
    });
        
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        [self hiddenProgressHUD];
        [self creatSubViews];
        
    });
    
}


-(void)initTalbeViewSubview{
    
    float textWidth =  250/WIDTH_6S_SCALE;
    float textX = SCREEN_WIDTH - textWidth - Space_X;
    float textHeigth = HeaderView_Height;

    
    _nameTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    _nameTF.returnKeyType = UIReturnKeyDone;
    [_nameTF setFont:kFontNameSize(14)];
    _nameTF.placeholder=@"请输入商品名称";
    _nameTF.delegate = self;
    _nameTF.textAlignment = NSTextAlignmentRight;
    _nameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //    _nameTF.inputAccessoryView = [self addToolbar];
    
    _priceTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_priceTF setFont:kFontNameSize(14)];
    _priceTF.placeholder=@"请输入商品进价";
    _priceTF.delegate = self;
    _priceTF.textAlignment = NSTextAlignmentRight;
    _priceTF.keyboardType = UIKeyboardTypeDecimalPad;
    _priceTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    

    _salesPriceTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_salesPriceTF setFont:kFontNameSize(14)];
    _salesPriceTF.placeholder=@"请输入商品售价";
    _salesPriceTF.delegate = self;
    _salesPriceTF.textAlignment = NSTextAlignmentRight;
    _salesPriceTF.keyboardType = UIKeyboardTypeDecimalPad;
    _salesPriceTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    _membersPriceTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_membersPriceTF setFont:kFontNameSize(14)];
    _membersPriceTF.placeholder=@"请输入商品会员价";
    _membersPriceTF.delegate = self;
    _membersPriceTF.textAlignment = NSTextAlignmentRight;
    _membersPriceTF.keyboardType = UIKeyboardTypeDecimalPad;
    _membersPriceTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    _packingPriceTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_packingPriceTF setFont:kFontNameSize(14)];
    _packingPriceTF.placeholder=@"请输入包装费用";
    _packingPriceTF.delegate = self;
    _packingPriceTF.textAlignment = NSTextAlignmentRight;
    _packingPriceTF.keyboardType = UIKeyboardTypeDecimalPad;
    _packingPriceTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    _countTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_countTF setFont:kFontNameSize(14)];
    _countTF.placeholder=@"请输入数量";
    _countTF.delegate = self;
    _countTF.textAlignment = NSTextAlignmentRight;
    _countTF.keyboardType = UIKeyboardTypeDecimalPad;
    _countTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    
    _minBuyPriceTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_minBuyPriceTF setFont:kFontNameSize(14)];
    _minBuyPriceTF.placeholder=@"请输入数量";
    _minBuyPriceTF.delegate = self;
    _minBuyPriceTF.textAlignment = NSTextAlignmentRight;
    _minBuyPriceTF.keyboardType = UIKeyboardTypeDecimalPad;
    _minBuyPriceTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    
    _kuCunRemindTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_kuCunRemindTF setFont:kFontNameSize(14)];
    _kuCunRemindTF.placeholder=@"请输入数量";
    _kuCunRemindTF.delegate = self;
    _kuCunRemindTF.textAlignment = NSTextAlignmentRight;
    _kuCunRemindTF.keyboardType = UIKeyboardTypeDecimalPad;
    _kuCunRemindTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    
    _goodsMiaoSuTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_goodsMiaoSuTF setFont:kFontNameSize(14)];
    _goodsMiaoSuTF.placeholder=@"请简单描述";
    _goodsMiaoSuTF.delegate = self;
    _goodsMiaoSuTF.textAlignment = NSTextAlignmentRight;
    _goodsMiaoSuTF.keyboardType = UIKeyboardTypeDefault;
    _goodsMiaoSuTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    _specialTF = [[UITextField alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_specialTF setFont:kFontNameSize(14)];
    _specialTF.placeholder=@"请以标签1,标签2,标签3的方式添加";
    _specialTF.delegate = self;
    _specialTF.textAlignment = NSTextAlignmentRight;
    _specialTF.keyboardType = UIKeyboardTypeDefault;
    _specialTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    
    
    _shangJiaLabel = [[UILabel alloc] initWithFrame:CGRectMake(textX, 0, textWidth, textHeigth)];
    [_shangJiaLabel setFont:kFontNameSize(14)];
    _shangJiaLabel.text = @"是";
    _shangJiaLabel.textAlignment = NSTextAlignmentRight;
    _shangJiaLabel.textColor = [UIColor blackColor];
    
    
    
//    _platformBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    _platformBtn.titleLabel.numberOfLines = 2;
//    _platformBtn.frame = CGRectMake(textX, 0, textWidth, textHeigth);
//    _platformBtn.titleLabel.font = kFontNameSize(14);
//    [_platformBtn setTitle:@"请选择平台分类 >" forState:UIControlStateNormal];
//    if ([_platformBtn.titleLabel.text isEqualToString:@"请选择平台分类 >"]) {
//        [_platformBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    } else {
//        [_platformBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    }
//    _platformBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [_platformBtn addTarget:self action:@selector(chooseButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _storeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _storeBtn.frame = CGRectMake(textX, 0, textWidth, textHeigth);
    _storeBtn.titleLabel.font = kFontNameSize(14);
    [_storeBtn setTitle:@"请选择店铺分类 >" forState:UIControlStateNormal];
    if ([_storeBtn.titleLabel.text isEqualToString:@"请选择店铺分类 >"]) {
        [_storeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    } else {
        [_storeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    _storeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_storeBtn addTarget:self action:@selector(chooseButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    _platformBtn.tag = 10001;
    _storeBtn.tag = 10002;
    
    _photoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), PhotoView_H)]; 
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake( Space_X, 0, SCREEN_WIDTH - Space_X , 30/HEIGHT_6S_SCALE)];
    titleLabel.text = @"图片(1张)";
    titleLabel.font = kFontNameSize(14);
    titleLabel.textColor = getColor(blackColor);
    [_photoView addSubview:titleLabel];
    
    
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titleLabel.frame), CGRectGetWidth(self.view.frame), PhotoView_H - CGRectGetMaxY(titleLabel.frame)) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.scrollEnabled = NO;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [_collectionView registerClass:[UpdatePhotoCollectionViewCell class] forCellWithReuseIdentifier:@"UpdatePhotoCollectionViewCell"];
    [_photoView addSubview:_collectionView];
    
    
   _itemWH = 60/HEIGHT_6S_SCALE;
    _margin = (CGRectGetHeight(_collectionView.frame) - _itemWH)/2;
    
    if (!self.isFaBu) {
       [self editorVCAssignmentWithDict:self.mainDict];
    }
    
}

- (void)editorVCAssignmentWithDict:(NSDictionary *)mainDict {
    
    NSLog(@"%@",mainDict);
    self.platformId = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"cat_id"]];
    self.typeId =[NSString stringWithFormat:@"%@",[mainDict objectForKey:@"user_cat"]];
    
//    if (![[mainDict objectForKey:@"cat_name_three"] isEqualToString:@""]) {
//        [self.platformBtn setTitle:[NSString stringWithFormat:@"%@-%@-%@",[mainDict objectForKey:@"cat_name_three"],[mainDict objectForKey:@"cat_name_two"],[mainDict objectForKey:@"cat_name_one"]] forState:UIControlStateNormal];
//        [self.platformBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    } else
//    {
//        [_platformBtn setTitle:@"请选择平台分类 >" forState:UIControlStateNormal];
//        [self.platformBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    }
    
    if (![[mainDict objectForKey:@"user_cat_name"] isEqualToString:@""]) {
        [self.storeBtn setTitle:[NSString stringWithFormat:@"%@",[mainDict objectForKey:@"user_cat_name"]] forState:UIControlStateNormal];
        [_storeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    } else {
        [_storeBtn setTitle:@"请选择店铺分类 >" forState:UIControlStateNormal];
         [_storeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
    self.nameTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"goods_name"]];
    self.priceTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"jinhuo_price"]];
    self.salesPriceTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"shop_price"]];
    self.membersPriceTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"members_price"]];
    self.packingPriceTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"pack_fee"]];
    self.countTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"goods_number"]];
    self.minBuyPriceTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"mix_num"]];
    self.kuCunRemindTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"warn_number"]];
    self.goodsMiaoSuTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"goods_desc"]];
    self.specialTF.text = [NSString stringWithFormat:@"%@",[mainDict objectForKey:@"goods_product_tag"]];
    
    if ([[mainDict objectForKey:@"is_on_sale"] isEqualToString:@"1"]) {
        self.shangJiaLabel.text = @"是";
    } else {
        self.shangJiaLabel.text = @"否";
    }
    
    if (mainDict != nil) {
        [_selectedPhotos removeAllObjects];
        UIImage *imgee = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[mainDict objectForKey:@"goods_img"]]]];
        if (imgee != nil) {
            [_selectedPhotos addObject:imgee];
            [_collectionView reloadData];
        }
    }
   
}

#pragma mark 提交按钮
-(UIView *)creatFooterView{
    
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, FooterButton_Height)];
    
    self.commitbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.commitbtn addTarget:self action:@selector(commitBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.commitbtn.layer.masksToBounds = YES;
    self.commitbtn.layer.cornerRadius = 10;
    self.commitbtn.titleLabel.font=kFontNameSize(16);
    [footerView addSubview:self.commitbtn];
    if (self.isFaBu) {
        [self.commitbtn setTitle:@"发布商品" forState:UIControlStateNormal];
    } else {
        [self.commitbtn setTitle:@"确认修改" forState:UIControlStateNormal];
    }
    self.commitbtn.backgroundColor=  getColor(greenBackColor);
    [self.commitbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.commitbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(FooterButton_Height/2);
        make.left.mas_equalTo(footerView).mas_offset(40);
        make.right.mas_equalTo(footerView).mas_offset(-40);
        make.centerY.mas_equalTo(footerView);
        
    }];
    
    
    return footerView;
}

#pragma mark - 点击区域 标签
- (void)chooseButtonClicked:(UIButton *)chooseButton{
    
    [self.view endEditing:YES];
    
    __weak typeof(self) weakSelf = self;
    
    if (chooseButton == self.platformBtn) {
        
        [CGXPickerView showAddressPickerWithTitle:@"平台分类" DataSource:self.platformArray DefaultSelected:@[@0, @0,@0] IsAutoSelect:NO Manager:nil ResultBlock:^(NSArray *selectAddressArr, NSArray *selectAddressRow,NSString *code) {
//            NSLog(@"%@-%@",selectAddressArr,selectAddressRow);
            NSLog(@"code = %@",code);
            
            self.platformId = code;
            NSString *textStr = [NSString stringWithFormat:@"%@-%@-%@", selectAddressArr[0], selectAddressArr[1],selectAddressArr[2]];
            
            [weakSelf.platformBtn setTitle:textStr forState:UIControlStateNormal];
            [weakSelf.platformBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
        }];
        
    }
    
    if (chooseButton == self.storeBtn) {
        
        NSMutableArray *array = [NSMutableArray array];
        for (MStore *model in self.storeArray) {
            [array addObject:model.cat_name];
        }
        [CGXPickerView showStringPickerWithTitle:@"店铺分类" DataSource:array DefaultSelValue:array.firstObject IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
//            NSLog(@"%@",selectValue);
            NSInteger index = [selectRow integerValue];
            MStore *model = self.storeArray[index];
            self.typeId = [NSString stringWithFormat:@"%@",model.cat_id];
            [self.storeBtn setTitle:[NSString stringWithFormat:@"%@",selectValue] forState:UIControlStateNormal];
            [self.storeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            NSLog(@"typeId = %@",self.typeId);
            
        }];
    }
}


#pragma mark -  UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"CELL_ID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = kFontNameSize(14);
//    cell.textLabel.textColor = [UIColor grayColor];
    if (cell.contentView.subviews.count > 0) {
        
        for (UIView *views in cell.contentView.subviews) {
            
            [views removeFromSuperview];
        }
    }


    if (indexPath.row == 0) {
        
        cell.textLabel.text = @"商品名称";
        cell.accessoryView = _nameTF;
        
    }else if (indexPath.row == 1){
        
//        cell.textLabel.text = @"平台分类";
//        cell.accessoryView = _platformBtn;
        cell.textLabel.text = @"店铺分类";
        cell.accessoryView = _storeBtn;
    }else if (indexPath.row == 2){
        
        cell.textLabel.text = @"进价";
        cell.accessoryView = _priceTF;
        
    }else if (indexPath.row == 3){
        
        cell.textLabel.text = @"售价";
        cell.accessoryView = _salesPriceTF;
        
    }else if (indexPath.row == 4){
        
        cell.textLabel.text = @"会员价";
        cell.accessoryView = _membersPriceTF;
        
    }else if (indexPath.row == 5){
        
        cell.textLabel.text = @"包装费";
        cell.accessoryView = _packingPriceTF;
        
    }else if (indexPath.row == 6){
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        lineView.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240.0/255.0 alpha:1];
        [cell.contentView addSubview:lineView];
        
    }else if (indexPath.row == 7){
        
        cell.textLabel.text = @"数量";
        cell.accessoryView = _countTF;
        
    }else if (indexPath.row == 8){
        
        cell.textLabel.text = @"最低购买数量";
        cell.accessoryView = _minBuyPriceTF;
        
    }else if (indexPath.row == 9){
        
        cell.textLabel.text = @"库存提醒";
        cell.accessoryView = _kuCunRemindTF;
        
    }else if (indexPath.row == 10){
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        lineView.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240.0/255.0 alpha:1];
        [cell.contentView addSubview:lineView];
        
    }else if (indexPath.row == 11){
        
        [cell.contentView addSubview:self.photoView];
        
    }else if (indexPath.row == 12){
        
        cell.textLabel.text = @"商品描述";
        cell.accessoryView = _goodsMiaoSuTF;
        
    }else if (indexPath.row == 13){
        
        cell.textLabel.text = @"特色标签";
        cell.accessoryView = _specialTF;
        
    }else {
        
        cell.textLabel.text = @"是否上架";
        cell.accessoryView = _shangJiaLabel;
        
    }
    
    return cell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 11 ) {
        return PhotoView_H;
    }else if (indexPath.row == 6 || indexPath.row == 10 ) {
        return 10;
    } else {
        return HeaderView_Height;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     if (indexPath.row == 14) {//是否上架
        
        [self.view endEditing:YES];
        NSArray *arr = @[@"是",@"否"];
        [CGXPickerView showStringPickerWithTitle:@"是否上架" DataSource:arr DefaultSelValue:arr.firstObject IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
            //            NSLog(@"%@",selectValue);
            self.shangJiaLabel.text = selectValue;
        }];
        
    }
}

#pragma mark - 点击提交评价按钮
-(void)commitBtnAction:(UIButton *)button{
    
    if (self.nameTF.text.length == 0) {
        ShowMessage(@"请输入商品名称");
        return;
    }
//    if ([_platformBtn.titleLabel.text rangeOfString:@"选择"].location != NSNotFound) {
//        ShowMessage(@"请选择平台分类");
//        return;
//    }
    if ([_storeBtn.titleLabel.text rangeOfString:@"选择"].location != NSNotFound) {
        ShowMessage(@"请选择店铺分类");
        return;
    }
    if (self.priceTF.text.length == 0) {
        ShowMessage(@"请输入商品进价");
        return;
    }
    
    if (self.salesPriceTF.text.length == 0) {
        ShowMessage(@"请输入商品售价");
        return;
    }
//    if (self.membersPriceTF.text.length == 0) {
//        ShowMessage(@"请输入商品会员价");
//        return;
//    }
    if (self.packingPriceTF.text.length == 0) {
        ShowMessage(@"请输入包装费用");
        return;
    }
    if (self.countTF.text.length == 0) {
        ShowMessage(@"请输入数量");
        return;
    }
    if (self.minBuyPriceTF.text.length == 0) {
        ShowMessage(@"请输入最低购买数量");
        return;
    }
    if (self.kuCunRemindTF.text.length == 0) {
        ShowMessage(@"请输入库存提醒数量");
        return;
    }
    if (self.goodsMiaoSuTF.text.length == 0) {
        ShowMessage(@"请输入商品描述");
        return;
    }
    
    if (self.specialTF.text.length == 0) {
        ShowMessage(@"请输入特色标签");
        return;
    }
    
    if (_selectedPhotos.count == 0) {
        ShowMessage(@"请添加照片");
        return;
    }
    
    if (!self.isFaBu) {//编辑商品
        [self editorConfirmChangeData];
        return;
    }
    [self commitChooseImageData];
  
}
//确认修改
- (void)editorConfirmChangeData{
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"edit_goods" forKey:@"ince"];
    [dic setValue:[UserModel sharedInstanced].ru_Id forKey:@"ru_id"];
    [dic setValue:self.nameTF.text forKey:@"goods_name"];
    [dic setValue:self.salesPriceTF.text forKey:@"price"];
    //[dic setValue:self.platformId forKey:@"cat_id"];
    [dic setValue:self.typeId forKey:@"user_cat_id"];
    [dic setValue:self.priceTF.text forKey:@"jinhuo_price"];
    [dic setValue:self.membersPriceTF.text forKey:@"members_price"];
    [dic setValue:self.packingPriceTF.text forKey:@"pack_fee"];
    [dic setValue:self.countTF.text forKey:@"goods_number"];
    [dic setValue:self.minBuyPriceTF.text forKey:@"mix_num"];
    [dic setValue:self.kuCunRemindTF.text forKey:@"warn_number"];
    [dic setValue:self.goodsMiaoSuTF.text forKey:@"goods_desc"];
    [dic setValue:self.specialTF.text forKey:@"goods_product_tag"];
    [dic setValue:self.goodsId forKey:@"goods_id"];
    if ([self.shangJiaLabel.text isEqualToString:@"是"]) {
        [dic setValue:@"1" forKey:@"is_on_sale"];
    } else {
        [dic setValue:@"0" forKey:@"is_on_sale"];
    }
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"edit_goods"];
    [mgr POST:URL parameters:dic progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            ShowMessage(responseObject[@"msg"]);
            [self performSelector:@selector(popView) withObject:nil afterDelay:1.5];
        } else {
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        [self hidHUD:@"网络异常"];
    }];
}




-(void)commitChooseImageData{
    
    NSMutableArray *originalArray = [NSMutableArray array];
    NSMutableArray *urlArray = [NSMutableArray array];
    NSMutableArray *goodsArray = [NSMutableArray array];
    
    for (int i = 0; i < _selectedPhotos.count ; i++) {
        
        UIImage *image = _selectedPhotos[i];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setValue:@"arr" forKey:@"ince"];
        [dic setValue:[UserModel sharedInstanced].ru_Id forKey:@"sid"];
        
        [NetRepositories requestAFURL:dic imageData:imageData complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
            
            
            NSString *original = response[@"original_img"];
            NSString *url = response[@"url"];
            NSString *goods = response[@"goods_img"];
            
            
            [originalArray addObject:original];
            [urlArray addObject:url];
            [goodsArray addObject:goods];
            
            if (i == _selectedPhotos.count -1) {
                // 更新界面
//                NSLog(@"originalArray  ===   %@",originalArray);
//                NSLog(@"urlArray  ===   %@",urlArray);
//                NSLog(@"goodsArray  ===   %@",goodsArray);
                [self commitDataWithOriginalArray:originalArray UrlArray:urlArray GoodsArray:goodsArray];
            }
            
        }];
        
       
    }
    
}
-(void)commitDataWithOriginalArray:(NSArray *)originalArray UrlArray:(NSArray *)urlArray GoodsArray:(NSArray *)goodsArray{
    
//    ince":"add_goods","goods_name":"123","goods_thumb":"http:\/\/xmshop.zadtek.com\/Public\/Uploads\/thumb\/1543976469.jpg,","price":"2","cat_id":"146","user_cat_id":"1524","sid":"101","original_img":"http:\/\/xmshop.zadtek.com\/Public\/Uploads\/1543976469.jpg,","goods_img":"http:\/\/xmshop.zadtek.com\/Public\/Uploads\/img\/1543976469.jpg,"
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"add_goods" forKey:@"ince"];
    [dic setValue:[UserModel sharedInstanced].ru_Id forKey:@"sid"];
    [dic setValue:self.nameTF.text forKey:@"goods_name"];
    [dic setValue:self.salesPriceTF.text forKey:@"price"];
   // [dic setValue:self.platformId forKey:@"cat_id"];
    [dic setValue:self.typeId forKey:@"user_cat_id"];
    
    [dic setValue:self.priceTF.text forKey:@"jinhuo_price"];
    [dic setValue:self.membersPriceTF.text forKey:@"members_price"];
    [dic setValue:self.packingPriceTF.text forKey:@"pack_fee"];
    [dic setValue:self.countTF.text forKey:@"goods_number"];
    [dic setValue:self.minBuyPriceTF.text forKey:@"mix_num"];
    [dic setValue:self.kuCunRemindTF.text forKey:@"warn_number"];
    [dic setValue:self.goodsMiaoSuTF.text forKey:@"goods_desc"];
    [dic setValue:self.specialTF.text forKey:@"goods_product_tag"];
    
    if ([self.shangJiaLabel.text isEqualToString:@"是"]) {
        [dic setValue:@"1" forKey:@"is_on_sale"];
    } else {
        [dic setValue:@"0" forKey:@"is_on_sale"];
    }
    
    
    if (originalArray.count != 0) {
        NSString *original = [originalArray componentsJoinedByString:@","];
        [dic setValue:original forKey:@"original_img"];
        NSString *url = [urlArray componentsJoinedByString:@","];
        [dic setValue:url forKey:@"goods_thumb"];
        NSString *goods = [goodsArray componentsJoinedByString:@","];
        [dic setValue:goods forKey:@"goods_img"];
        
    }else{
        [dic setValue:@"" forKey:@"original_img"];
        [dic setValue:@"" forKey:@"goods_thumb"];
        [dic setValue:@"" forKey:@"goods_img"];
        
    }
    NSLog(@"dic = %@",dic);
    [NetRepositories netConfirm:dic complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        [WMHelper outPutJsonString:response];
        
        NSInteger flag = [[response objectForKey:@"ret"]integerValue];
        if(flag == 200){
            ShowMessage(message);
            [self performSelector:@selector(popView) withObject:nil afterDelay:1.5];
        } else {
            ShowMessage(message);
        }

    }];
      
    
}
-(void)popView{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -  UITextField
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}


//限制输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.priceTF) {
        if (string.length == 0){
            return YES;
        }else{
            NSInteger existedLength = textField.text.length;
            NSInteger selectedLength = range.length;
            NSInteger replaceLength = string.length;
            if (existedLength - selectedLength + replaceLength > 11) {
                return NO;
            }
        }
        
    }
    
    
    NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
    [str insertString:string atIndex:range.location];
    
    if (textField == self.priceTF) {
        
        if (string.length != 0 ){
            
            //限制输入
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
            NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            BOOL basicTest = [string isEqualToString:filtered];
            if (!basicTest) {
                return NO;
            }else{
                return YES;
            }
            
        }
        
        
    }
    
    return YES;
}
#pragma mark -  UIImagePickerController
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        if (iOS7Later) {
            _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        }
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}
#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_selectedPhotos.count >= maxCount) {
        return _selectedPhotos.count;
    }
    for (PHAsset *asset in _selectedAssets) {
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            return _selectedPhotos.count;
        }
    }
    
    return _selectedPhotos.count + 1;
}
#pragma mark -- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(_itemWH, _itemWH);
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(_margin, _margin, _margin, _margin);;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return _margin;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return _margin;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UpdatePhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UpdatePhotoCollectionViewCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.item == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn"];
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.item];
        
        if (self.isFaBu) {
            cell.asset = _selectedAssets[indexPath.item];
            cell.deleteBtn.hidden = NO;
        } else {
            cell.deleteBtn.hidden = YES;
        }
    }
    
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == _selectedPhotos.count) {
        //        BOOL showSheet = self.showSheetSwitch.isOn;
        //        if (showSheet) {
        //            NSString *takePhotoTitle = @"拍照";
        //            if (self.showTakeVideoBtnSwitch.isOn && self.showTakePhotoBtnSwitch.isOn) {
        //                takePhotoTitle = @"相机";
        //            } else if (self.showTakeVideoBtnSwitch.isOn) {
        //                takePhotoTitle = @"拍摄";
        //            }
        //            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:takePhotoTitle,@"去相册选择", nil];
        //            [sheet showInView:self.view];
        //        } else {
        [self pushTZImagePickerController];
        //        }
    } else { // preview photos or video / 修改照片
        
        if (!self.isFaBu) {
            [self updateAvatarImage];
            return;
        }
        
        
        
        id asset = _selectedAssets[indexPath.item];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = asset;
            isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
        }
        //        if ([[asset valueForKey:@"filename"] tz_containsString:@"GIF"] && self.allowPickingGifSwitch.isOn && !self.allowPickingMuitlpleVideoSwitch.isOn) {
        //            TZGifPhotoPreviewController *vc = [[TZGifPhotoPreviewController alloc] init];
        //            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhotoGif timeLength:@""];
        //            vc.model = model;
        //            [self presentViewController:vc animated:YES completion:nil];
        //        } else if (isVideo && !self.allowPickingMuitlpleVideoSwitch.isOn) { // perview video / 预览视频
        //            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
        //            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
        //            vc.model = model;
        //            [self presentViewController:vc animated:YES completion:nil];
        //        } else { // preview photos / 预览照片
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.item];
        imagePickerVc.maxImagesCount = maxCount;
        imagePickerVc.allowPickingMultipleVideo = NO;
        imagePickerVc.showSelectedIndex = YES;
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.allowPickingGif = NO;


        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            self->_selectedPhotos = [NSMutableArray arrayWithArray:photos];
            self->_selectedAssets = [NSMutableArray arrayWithArray:assets];
            self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
            [self->_collectionView reloadData];
            self->_collectionView.contentSize = CGSizeMake(0, ((self->_selectedPhotos.count + 2) / 3 ) * (self->_margin + self->_itemWH));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        //        }
    }
}


#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    if (maxCount <= 0) {
        return;
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCount columnNumber:maxCount delegate:self pushPhotoPickerVc:YES];
    // imagePickerVc.navigationBar.translucent = NO;
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    if (maxCount > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    
    // imagePickerVc.photoWidth = 1000;
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // if (iOS7Later) {
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // }
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    /*
     [imagePickerVc setAssetCellDidSetModelBlock:^(TZAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
     cell.contentView.clipsToBounds = YES;
     cell.contentView.layer.cornerRadius = cell.contentView.tz_width * 0.5;
     }];
     */
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo =NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    //     imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.needCircleCrop = NO;
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = SCREEN_WIDTH - 2 * left;
    NSInteger top = (SCREEN_HEIGHT - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    // 设置横屏下的裁剪尺寸
    // imagePickerVc.cropRectLandscape = CGRectMake((self.view.tz_height - widthHeight) / 2, left, widthHeight, widthHeight);
    /*
     [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
     cropView.layer.borderColor = [UIColor redColor].CGColor;
     cropView.layer.borderWidth = 2.0;
     }];*/
    
    //imagePickerVc.allowPreview = NO;
    // 自定义导航栏上的返回按钮
    /*
     [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){
     [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
     [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
     }];
     imagePickerVc.delegate = self;
     */
    
    // Deprecated, Use statusBarStyle
    // imagePickerVc.isStatusBarDefault = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    
    // 设置首选语言 / Set preferred language
    // imagePickerVc.preferredLanguage = @"zh-Hans";
    
    // 设置languageBundle以使用其它语言 / Set languageBundle to use other language
    // imagePickerVc.languageBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"tz-ru" ofType:@"lproj"]];
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
//        self.photosArray = [NSMutableArray arrayWithArray:photos];
//        self.assetsArray = [NSMutableArray arrayWithArray:assets];
       
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

/*
 // 设置了navLeftBarButtonSettingBlock后，需打开这个方法，让系统的侧滑返回生效
 - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
 
 navigationController.interactivePopGestureRecognizer.enabled = YES;
 if (viewController != navigationController.viewControllers[0]) {
 navigationController.interactivePopGestureRecognizer.delegate = nil; // 支持侧滑
 }
 }
 */

#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        //        if (self.showTakeVideoBtnSwitch.isOn) {
        //            [mediaTypes addObject:(NSString *)kUTTypeMovie];
        //        }
        //        if (self.showTakePhotoBtnSwitch.isOn) {
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        //        }
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        if (iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // take photo / 去拍照
        [self takePhoto];
    } else if (buttonIndex == 1) {
        [self pushTZImagePickerController];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    // 1.打印图片名字
    [self printAssetsName:assets];
    // 2.图片位置信息
    if (iOS8Later) {
        for (PHAsset *phAsset in assets) {
            NSLog(@"location:%@",phAsset.location);
        }
    }
    
    /*
     // 3. 获取原图的示例，这样一次性获取很可能会导致内存飙升，建议获取1-2张，消费和释放掉，再获取剩下的
     __block NSMutableArray *originalPhotos = [NSMutableArray array];
     __block NSInteger finishCount = 0;
     for (NSInteger i = 0; i < assets.count; i++) {
     [originalPhotos addObject:@1];
     }
     for (NSInteger i = 0; i < assets.count; i++) {
     PHAsset *asset = assets[i];
     [[TZImageManager manager] getOriginalPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info) {
     finishCount += 1;
     [originalPhotos replaceObjectAtIndex:i withObject:photo];
     if (finishCount >= assets.count) {
     NSLog(@"All finished.");
     }
     }];
     }
     */
}

// If user picking a video, this callback will be called.
// If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
// 如果用户选择了一个视频，下面的handle会被执行
// 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    // open this code to send video / 打开这段代码发送视频
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPreset640x480 success:^(NSString *outputPath) {
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        // Export completed, send video here, send by outputPath or NSData
        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

// If user picking a gif image, this callback will be called.
// 如果用户选择了一个gif图片，下面的handle会被执行
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    [_collectionView reloadData];
}

// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    /*
     if ([albumName isEqualToString:@"个人收藏"]) {
     return NO;
     }
     if ([albumName isEqualToString:@"视频"]) {
     return NO;
     }*/
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    /*
     if (iOS8Later) {
     PHAsset *phAsset = asset;
     switch (phAsset.mediaType) {
     case PHAssetMediaTypeVideo: {
     // 视频时长
     // NSTimeInterval duration = phAsset.duration;
     return NO;
     } break;
     case PHAssetMediaTypeImage: {
     // 图片尺寸
     if (phAsset.pixelWidth > 3000 || phAsset.pixelHeight > 3000) {
     // return NO;
     }
     return YES;
     } break;
     case PHAssetMediaTypeAudio:
     return NO;
     break;
     case PHAssetMediaTypeUnknown:
     return NO;
     break;
     default: break;
     }
     } else {
     ALAsset *alAsset = asset;
     NSString *alAssetType = [[alAsset valueForProperty:ALAssetPropertyType] stringValue];
     if ([alAssetType isEqualToString:ALAssetTypeVideo]) {
     // 视频时长
     // NSTimeInterval duration = [[alAsset valueForProperty:ALAssetPropertyDuration] doubleValue];
     return NO;
     } else if ([alAssetType isEqualToString:ALAssetTypePhoto]) {
     // 图片尺寸
     CGSize imageSize = alAsset.defaultRepresentation.dimensions;
     if (imageSize.width > 3000) {
     // return NO;
     }
     return YES;
     } else if ([alAssetType isEqualToString:ALAssetTypeUnknown]) {
     return NO;
     }
     }*/
    return YES;
}

#pragma mark - Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    if ([self collectionView:self.collectionView numberOfItemsInSection:0] <= _selectedPhotos.count) {
        [_selectedPhotos removeObjectAtIndex:sender.tag];
        [_selectedAssets removeObjectAtIndex:sender.tag];
        [self.collectionView reloadData];
        return;
    }
    
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self->_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_collectionView reloadData];
    }];
}


#pragma mark - Private

/// 打印图片名字
- (void)printAssetsName:(NSArray *)assets {
    NSString *fileName;
    for (id asset in assets) {
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = (PHAsset *)asset;
            fileName = [phAsset valueForKey:@"filename"];
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = (ALAsset *)asset;
            fileName = alAsset.defaultRepresentation.filename;;
        }
        // NSLog(@"图片名字:%@",fileName);
    }
}

#pragma mark - 上传头像
- (void)updateAvatarImage
{
    
    self.navigationController.navigationBar.hidden = NO;
    UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.navigationBar.translucent = NO;
    imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsEditing = YES;
    
    // 判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 设置数据源
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:cameraAction];
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:photoAction];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertSheet addAction:cancelAction];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertSheet animated:YES completion:nil];
    });
    
    
}



#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])        // 被选中的图片
    {
        // 获取照片
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [picker dismissViewControllerAnimated:YES completion:nil];          // 隐藏视图
        
        [self commitUserAvatarDataWithImage:image];
    }
}

#pragma mark - 提交用户头像
-(void)commitUserAvatarDataWithImage:(UIImage *)image{
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:@"arr" forKey:@"ince"];
    [dic setValue:[UserModel sharedInstanced].ru_Id forKey:@"sid"];
    
    [NetRepositories requestAFURL:dic imageData:imageData complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        
        NSLog(@"response = %@",response);
        ShowMessage(response[@"msg"]);
        
        NSString *original = response[@"original_img"];
        NSString *url = response[@"url"];
        NSString *goods = response[@"goods_img"];
        
        NSDictionary* arg =  @{@"ince":@"update_goods_img",
                               @"sid":[UserModel sharedInstanced].ru_Id,
                               @"goods_id": self.goodsId,
                               @"url":url,
                               @"goods_img":goods,
                               @"original_img":original
                               };
        [NetRepositories netConfirm:arg complete:^(EnumNetResponse react,NSDictionary* response ,NSString *message) {
            if(react == NetResponseSuccess){
                ShowMessage(message);
                NSString* iamge = [response objectForKey: @"goods_img"];
                //self.currentGoods.thumbnail = iamge;
                [_selectedPhotos removeAllObjects];
                UIImage *imgee = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:iamge]]];
                [_selectedPhotos addObject:imgee];
                [_collectionView reloadData];
            }else if (react == NetResponseException){
                ShowMessage(message);
            }else{
                ShowMessage(message);
            }
        }];
        
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
